import React, { useEffect, useMemo, useState } from 'react';
import { Space, Form, Input, DatePicker, Button, Table, Tag, Modal, Pagination, Image, Select, InputNumber, Switch, Card } from 'antd';
import { PictureOutlined, StarOutlined, EditOutlined, DeleteOutlined, SearchOutlined, ReloadOutlined, PlusOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import './collect.css';

// 模拟接口数据（收藏列表）
const mockActivities = Array.from({ length: 20 }).map((_, i) => ({
  id: 1000 + i,
  name: `活动${i + 1}`,
  photoQrCode: 'https://oss.reyeah.com/reyeah/20240328/1711594443337-4053dc61-0092-4f93-8c20-8b6bfc855ebd.png',
  photoPassword: i % 3 === 0 ? '123456' : '',
  startTime: `2025-10-${String(1 + (i % 28)).padStart(2, '0')} 10:00:00`,
  endTime: `2025-10-${String(1 + (i % 28)).padStart(2, '0')} 18:00:00`,
  createTime: `2025-09-${String(1 + (i % 28)).padStart(2, '0')} 09:00:00`,
  printNum: Math.floor(Math.random() * 50),
  photoNum: Math.floor(Math.random() * 200),
  cloudPhotoSwitch: i % 2,
  isRetain: 1, // 收藏
  userMachineId: '1,2,3',
  electronicSwitch: i % 2,
  uploadSwitch: i % 2,
  electronicPrice: i % 2 ? 9.9 : 0,
}));

export default function Collect() {
  // 查询条件
  const [searchInfo, setSearchInfo] = useState({ activityName: '', id: '', activityStartTime: '', activityEndTime: '', startTime: '', endTime: '' });
  const [searchDateActivity, setSearchDateActivity] = useState([null, null]);
  const [searchDateCreate, setSearchDateCreate] = useState([null, null]);

  // 列表数据
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  // 相册弹窗
  const [albumOpen, setAlbumOpen] = useState(false);
  const [albumPage, setAlbumPage] = useState({ pageNum: 1, pageSize: 9, total: 0, activityId: null });
  const [albumList, setAlbumList] = useState([]);

  // 编辑弹窗
  const [editOpen, setEditOpen] = useState(false);
  const [editInfo, setEditInfo] = useState({ name: '', photoPassword: '', uploadSwitch: 0, cloudPhotoSwitch: 0, electronicSwitch: 0, electronicPrice: 0, startTime: '', endTime: '', userMachineId: '' });
  // 已取消顶部 Tabs

  useEffect(() => {
    handleSearch();
  }, []);

  function handleSearch() {
    setLoading(true);
    setTimeout(() => {
      const filtered = mockActivities.filter(a => a.isRetain === 1).filter(a => {
        const matchName = searchInfo.activityName ? a.name.includes(searchInfo.activityName) : true;
        const matchId = searchInfo.id ? String(a.id).includes(String(searchInfo.id)) : true;
        const matchActivityRange = searchInfo.activityStartTime && searchInfo.activityEndTime ? (a.startTime >= searchInfo.activityStartTime && a.endTime <= searchInfo.activityEndTime) : true;
        const matchCreateRange = searchInfo.startTime && searchInfo.endTime ? (a.createTime >= searchInfo.startTime && a.createTime <= searchInfo.endTime) : true;
        return matchName && matchId && matchActivityRange && matchCreateRange;
      });
      setRows(filtered);
      setLoading(false);
    }, 300);
  }

  function resetFilters() {
    setSearchInfo({ activityName: '', id: '', activityStartTime: '', activityEndTime: '', startTime: '', endTime: '' });
    setSearchDateActivity([null, null]);
    setSearchDateCreate([null, null]);
    handleSearch();
  }

  function handlerDateUpdate(value, name) {
    if (name === 'searchDateActivity') {
      setSearchDateActivity(value);
      setSearchInfo(prev => ({ ...prev, activityStartTime: value?.[0] || '', activityEndTime: value?.[1] || '' }));
    } else if (name === 'searchDateCreate') {
      setSearchDateCreate(value);
      setSearchInfo(prev => ({ ...prev, startTime: value?.[0] || '', endTime: value?.[1] || '' }));
    }
  }

  function handlerOpenAlbum(row) {
    setAlbumPage({ pageNum: 1, pageSize: 9, total: 36, activityId: row.id });
    // 模拟相册列表
    const imgs = Array.from({ length: 36 }).map((_, i) => ({ id: i + 1, url: row.photoQrCode }));
    setAlbumList(imgs.slice(0, 9));
    setAlbumOpen(true);
  }

  function handlerChangeAlbumPage(pageNum) {
    setAlbumPage(prev => ({ ...prev, pageNum }));
    const start = (pageNum - 1) * albumPage.pageSize;
    const end = start + albumPage.pageSize;
    const imgs = Array.from({ length: 36 }).map((_, i) => ({ id: i + 1, url: 'https://oss.reyeah.com/reyeah/20240328/1711594443337-4053dc61-0092-4f93-8c20-8b6bfc855ebd.png' }));
    setAlbumList(imgs.slice(start, end));
  }

  function handlerCollect(ids, isRetain) {
    Modal.confirm({
      title: '取消收藏',
      content: '确定取消收藏该活动吗？',
      onOk: () => {
        const idSet = new Set(Array.isArray(ids) ? ids : [ids]);
        setRows(prev => prev.filter(r => !idSet.has(r.id)));
        setSelectedRowKeys([]);
      }
    });
    // 模拟：取消收藏后从列表移除
  }

  function handlerDel(row) {
    Modal.confirm({
      title: '删除活动',
      content: '确定删除该活动吗？',
      onOk: () => setRows(prev => prev.filter(r => r.id !== row.id))
    });
  }

  function handlerInsert(row) {
    // 打开编辑弹窗并回显数据
    setEditInfo({
      name: row?.name || '',
      photoPassword: row?.photoPassword || '',
      uploadSwitch: row?.uploadSwitch || 0,
      cloudPhotoSwitch: row?.cloudPhotoSwitch || 0,
      electronicSwitch: row?.electronicSwitch || 0,
      electronicPrice: row?.electronicPrice || 0,
      startTime: row?.startTime || '',
      endTime: row?.endTime || '',
      userMachineId: row?.userMachineId || '',
    });
    setEditOpen(true);
  }

  function handleEditSubmit() {
    if (!editInfo.name) { alert('请输入活动名称'); return; }
    if (!editInfo.startTime || !editInfo.endTime) { alert('请选择活动范围时间'); return; }
    alert('保存成功（模拟）');
    setEditOpen(false);
  }

  const columns = [
    { title: 'ID', dataIndex: 'id', width: 100 },
    { title: '活动名称', dataIndex: 'name', width: 140, ellipsis: true },
    { title: '二维码', dataIndex: 'photoQrCode', width: 120, render: (src) => (<Image width={100} height={100} src={src} />) },
    { title: '照片密码', dataIndex: 'photoPassword', width: 120, ellipsis: true, render: (val) => val || '-' },
    { title: '开始时间', dataIndex: 'startTime', width: 180, ellipsis: true },
    { title: '结束时间', dataIndex: 'endTime', width: 180, ellipsis: true },
    { title: '创建时间', dataIndex: 'createTime', width: 180, ellipsis: true },
    { title: '打印数量', dataIndex: 'printNum', width: 120 },
    { title: '照片数量', dataIndex: 'photoNum', width: 120 },
    { title: '云相册', dataIndex: 'cloudPhotoSwitch', width: 100, render: (val) => val === 1 ? <Tag color="green">开启</Tag> : <Tag color="red">关闭</Tag> },
    {
      title: '操作', key: 'actions', fixed: 'right', align: 'right', width: 260,
      render: (_, row) => (
        <Space>
          <Button size="small" icon={<PictureOutlined />} onClick={() => handlerOpenAlbum(row)}>相册管理</Button>
          <Button size="small" icon={<StarOutlined />} type="dashed" danger onClick={() => handlerCollect([row.id], 0)}>取消收藏</Button>
          <Button size="small" icon={<EditOutlined />} type="primary" onClick={() => handlerInsert(row)}>编辑</Button>
          <Button size="small" icon={<DeleteOutlined />} danger onClick={() => handlerDel(row)}>删除</Button>
        </Space>
      )
    }
  ];

  return (
    <div className="collect-page">
      <Space direction="vertical" style={{ width: '100%' }} size={16}>
        {/* 顶部操作（已取消 Tabs） */}
        <Card
          title="活动管理 - 收藏列表"
          extra={
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => handlerInsert(null)}
              >新增活动</Button>
              <Button
                danger
                icon={<StarOutlined />}
                disabled={selectedRowKeys.length === 0}
                onClick={() => handlerCollect(selectedRowKeys, 0)}
              >批量取消收藏</Button>
            </Space>
          }
        >
          <Form layout="inline" onFinish={handleSearch}>
          <Form.Item label="活动名称">
            <Input
              value={searchInfo.activityName}
              placeholder="请输入活动名称"
              onChange={e => setSearchInfo(prev => ({ ...prev, activityName: e.target.value }))}
              allowClear
              style={{ width: 220 }}
            />
          </Form.Item>
          <Form.Item label="活动ID">
            <Input
              value={searchInfo.id}
              placeholder="请输入活动ID"
              onChange={e => setSearchInfo(prev => ({ ...prev, id: e.target.value }))}
              allowClear
              style={{ width: 200 }}
            />
          </Form.Item>
          <Form.Item label="活动范围">
            <DatePicker.RangePicker
              showTime
              value={[searchDateActivity[0] ? dayjs(searchDateActivity[0]) : null, searchDateActivity[1] ? dayjs(searchDateActivity[1]) : null]}
              onChange={(vals) => handlerDateUpdate(vals ? [vals[0]?.format('YYYY-MM-DD HH:mm:ss'), vals[1]?.format('YYYY-MM-DD HH:mm:ss')] : [null, null], 'searchDateActivity')}
            />
          </Form.Item>
          <Form.Item label="创建时间">
            <DatePicker.RangePicker
              showTime
              value={[searchDateCreate[0] ? dayjs(searchDateCreate[0]) : null, searchDateCreate[1] ? dayjs(searchDateCreate[1]) : null]}
              onChange={(vals) => handlerDateUpdate(vals ? [vals[0]?.format('YYYY-MM-DD HH:mm:ss'), vals[1]?.format('YYYY-MM-DD HH:mm:ss')] : [null, null], 'searchDateCreate')}
            />
          </Form.Item>
          <Form.Item>
            <Space style={{ marginLeft: 2 , marginTop: 12 }}>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />} loading={loading} style={{ height: 36 }}>查询</Button>
              <Button icon={<ReloadOutlined />} onClick={resetFilters} style={{ height: 36 }}>重置</Button>
            </Space>
          </Form.Item>
          </Form>
        </Card>
        <Card>
          <Table
          rowKey="id"
          bordered
          loading={loading}
          dataSource={rows}
          columns={columns}
          scroll={{ x: 1200 }}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
          }}
          />
        </Card>
      </Space>

      {/* 相册弹窗 */}
      <Modal
        open={albumOpen}
        title="相册管理"
        width={1100}
        onCancel={() => setAlbumOpen(false)}
        footer={null}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <div className="album-grid">
            {albumList.length === 0 ? (
              <div className="empty">暂无相册</div>
            ) : albumList.map(item => (
              <div key={item.id} className="album-item">
                <Image src={item.url} width={'100%'} height={160} />
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <Pagination
              current={albumPage.pageNum}
              pageSize={albumPage.pageSize}
              total={albumPage.total}
              onChange={handlerChangeAlbumPage}
              showTotal={(total) => `共 ${total} 条`}
            />
            <Button onClick={() => setAlbumOpen(false)}>关闭</Button>
          </div>
        </Space>
      </Modal>

      {/* 编辑弹窗 */}
      <Modal
        open={editOpen}
        title="编辑活动"
        width={600}
        onCancel={() => setEditOpen(false)}
        onOk={handleEditSubmit}
        okText="保存"
        cancelText="取消"
      >
        <Form layout="vertical">
          <Form.Item label="活动名称" required>
            <Input value={editInfo.name} onChange={e => setEditInfo(prev => ({ ...prev, name: e.target.value }))} />
          </Form.Item>
          <Form.Item label="照片密码">
            <Input value={editInfo.photoPassword} onChange={e => setEditInfo(prev => ({ ...prev, photoPassword: e.target.value }))} />
          </Form.Item>
          <Form.Item label="活动范围" required>
            <DatePicker.RangePicker
              showTime
              value={[editInfo.startTime ? dayjs(editInfo.startTime) : null, editInfo.endTime ? dayjs(editInfo.endTime) : null]}
              onChange={(vals) => setEditInfo(prev => ({ ...prev, startTime: vals?.[0]?.format('YYYY-MM-DD HH:mm:ss') || '', endTime: vals?.[1]?.format('YYYY-MM-DD HH:mm:ss') || '' }))}
            />
          </Form.Item>
          <Form.Item label="上传开关">
            <Switch checked={!!editInfo.uploadSwitch} onChange={(checked) => setEditInfo(prev => ({ ...prev, uploadSwitch: checked ? 1 : 0 }))} />
          </Form.Item>
          <Form.Item label="云相册">
            <Switch checked={!!editInfo.cloudPhotoSwitch} onChange={(checked) => setEditInfo(prev => ({ ...prev, cloudPhotoSwitch: checked ? 1 : 0 }))} />
          </Form.Item>
          <Form.Item label="电子底片">
            <Switch checked={!!editInfo.electronicSwitch} onChange={(checked) => setEditInfo(prev => ({ ...prev, electronicSwitch: checked ? 1 : 0 }))} />
          </Form.Item>
          <Form.Item label="底片价格">
            <InputNumber min={0} step={0.1} value={editInfo.electronicPrice} onChange={(val) => setEditInfo(prev => ({ ...prev, electronicPrice: Number(val || 0) }))} />
          </Form.Item>
          <Form.Item label="设备ID列表">
            <Input value={editInfo.userMachineId} onChange={e => setEditInfo(prev => ({ ...prev, userMachineId: e.target.value }))} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}